package com.splic.product.service.impl.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.splic.common.core.DeviceContext;
import com.splic.common.enums.OrderStatusEnum;
import com.splic.common.exception.BusinessException;
import com.splic.common.utils.StringUtils;
import com.splic.product.domain.Order;
import com.splic.product.domain.Product;
import com.splic.product.dto.CreateOrderDto;
import com.splic.product.dto.CreateOrderReturnDto;
import com.splic.product.service.OrderService;
import com.splic.product.service.ProductService;
import com.splic.product.service.ThirdPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.alipay.api.AlipayConstants.*;

/**
 * ==========================
 * 开发：yuxiangjie
 * 创建时间：2022-03-18 15:32
 * 版本: 1.0
 * 描述：TODO
 * ==========================
 */
@Service
@Slf4j
public class AlipayPayService implements ThirdPayService {


    @Autowired
    private ProductService productServiceImpl;

    @Autowired
    private OrderService orderServiceImpl;

    @Override
    public CreateOrderReturnDto createPayOrder(Order order, CreateOrderDto dto) {

        Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
        if (product == null){
            throw new BusinessException("应用获取失败");
        }

        JSONObject jsonObject = JSONObject.parseObject(product.getAlipayConfig());
        if (jsonObject == null){
            throw new BusinessException("应用支付参数获取失败");
        }

        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setNotifyUrl(jsonObject.getString("notify_url"));
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", order.getOrderNo());
        bizContent.put("total_amount", order.getAmount());
        bizContent.put("subject", order.getGoodsName());

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        request.setBizContent(bizContent.toString());
        CreateOrderReturnDto returnDto = new CreateOrderReturnDto();

        AlipayTradeAppPayResponse response = null;
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            response = getAliPayClient(jsonObject).sdkExecute(request);
        } catch (AlipayApiException e) {
            log.error("创建支付宝支付订单失败:{}",e);
        }
        returnDto.setBody(response.getBody());
        return returnDto;
    }

    @Override
    public int checkOrder(Order order) {
        Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
        if (product != null){
            JSONObject jsonObject = JSONObject.parseObject(product.getAlipayConfig());
            if (jsonObject != null){
                AlipayTradeQueryRequest queryRequest = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel model = new AlipayTradeQueryModel();
                model.setOutTradeNo(order.getOrderNo());
                queryRequest.setBizModel(model);
                AlipayTradeQueryResponse response = null;
                try {
                    response = getAliPayClient(jsonObject).execute(queryRequest);
                } catch (AlipayApiException e) {
                    log.error("支付宝查询订单" + order.getOrderNo() + "失败！", e);
                }
                if (response != null) {
                    if (response.isSuccess()) {
                        if (response.getTradeStatus().equals("TRADE_SUCCESS") || response.getTradeStatus().equals("TRADE_FINISHED")) {
                            // 更新订单状态
                            order.setStatus(OrderStatusEnum.PAY_SUCCESS.getCode());
                            orderServiceImpl.updateOrderStatus(order);
                            return 0;
                        } else {
                            log.error("支付宝订单" + order.getOrderNo() + "交易失败，交易状态：" + response.getTradeStatus());
                        }
                    } else {
                        log.error("支付宝订单" + order.getOrderNo() + "查询失败！");

                    }
                } else {
                    log.error("支付宝未获取订单" + order.getOrderNo() + "详情！");
                }

            } else {
                log.error("应用支付参数获取失败");
            }
        } else {
            log.error("应用获取失败");
        }
        return -1;
    }


    public AlipayClient getAliPayService(){
        Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
        if (product == null){
            throw new BusinessException("应用获取失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(product.getAlipayConfig());
        if (jsonObject == null){
            throw new BusinessException("应用支付参数获取失败");
        }

        return getAliPayClient(jsonObject);
    }

     public AlipayClient getAliPayClient(JSONObject jsonObject){

        AlipayClient alipayClient = new DefaultAlipayClient(
                jsonObject.getString("service_url"),
                jsonObject.getString("appid"),
                jsonObject.getString("private_key"),
                FORMAT_JSON, CHARSET_UTF8,
                jsonObject.getString("alipay_public_key"),
                SIGN_TYPE_RSA2);
        return alipayClient;
    }


}
